import axios from 'axios'
//var Global = getCurrentInstance().proxy
import Global from '../hooks/useGlobalData'
const apiUrl = process.env.NODE_ENV == 'development.' ? '//192.168.6.95:65533' : 'https:///www.androidgmt.com/manager'
const rootUrl = process.env.NODE_ENV == 'development' ? '/' : 'https:///www.androidgmt.com/android'

axios.defaults.baseURL = apiUrl
axios.defaults.withCredentials = true
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.timeout = 600000;

axios.interceptors.request.use(
  config => {
    let token = Global.VAR_DATA.user.token
    // console.log(token)
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    return config;
  },
  error => {
  //console.log(error)
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    if (response && response.status == 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    return Promise.resolve(error);
  }
);

function http(url, method, data ,cb) {
  //if (data.loading) loading = ElLoading.service({ fullscreen: false })
  let flag = ''
  if (url == '/AndroidPlatService/Files/FileUpload') flag = 'APP_UPLOAD'
  let postdata = method == 'post' ? data : ''
  let getdata = method == 'get' ? data : ''
  if (flag == 'APP_UPLOAD') axios.defaults.headers.post['Content-Type'] = 'multipart/form-data'
  return new Promise((resolve, reject) => {
    axios({
      method,
      url,
      data: postdata,
      params: getdata,
      onUploadProgress: function(progressEvent) { 
        let complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
        // complete
        // console.log('上传进度' + complete + '%')
        cb(complete)
      }
    })
    .then(res => {
    //console.log(res)
      let d = res
      if (d.status == 200) {
        d = d.data
      } else {
        d.returnCode == 40001
        if (d.response && d.response.data) {
          d.message = d.response.data
        }
      }
      // if (d.returnCode == 40001) {
      //   ElNotification({
      //     type: 'warning',
      //     title: flag+'失败',
      //     message: d.message
      //   })
      // }
      resolve(d)
    })
    .catch(err => {
    //console.log(typeof(err))
      if (typeof(err)=='object') {
        if (!err.returnCode) err.returnCode = 40001
      } else {
        err = {returnCode: 40001,message: JSON.stringify(err)}
      } 
      resolve(err)
      // ElNotification({
      //   type: 'error',
      //   title: '应用上传失败',
      //   message: typeof(err)=='object'?err.message:JSON.stringify(err)
      // })
      // reject(err)
    });
  })
}

export default {
  apiUrl, rootUrl, http,
}
